package myservice.android.activities;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import myservice.android.utilities.EditTextMonitor;
import myservice.android.utilities.ListRow;
import myservice.android.utilities.NumberPicker;
import myservice.android.utilities.NumberPicker.OnNumberPickerClosedListener;
import myservice.android.utilities.PopupMenu;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

public class MinistryDetailsActivity extends BaseSaveableActivity {
	
	private LinearLayout callList;
	private int ministryTimeHours, ministryTimeMinutes, creditTimeHours, creditTimeMinutes;
	private TextView ministryTimeValue, creditTimeValue, magazinesValue, booksValue, brochuresValue, tractsValue, videosValue, returnCallsValue;
	private TableRow ministryTimeRow, creditTimeRow, magazinesRow, booksRow, brochuresRow, tractsRow, videosRow, returnCallsRow; 
	private EditText commentsText;
	private TextView noCallsView;
	private Button saveButton, addCallButton;
	
	private int date,month,year;
	private boolean newRecord;	
	
	private class OnTimeClickListener implements OnClickListener {
		
		private static final int MINISTRY_TIME = 1;
		private static final int CREDIT_TIME = 2;			
		
		private int timeType;
		
		public OnTimeClickListener(int timeType) {
			super();
			this.timeType = timeType;
		}

		@Override
		public void onClick(View arg0) {
			final Dialog dialog = new Dialog(MinistryDetailsActivity.this);
			dialog.setContentView(R.layout.time_picker_dialog);
			
			if (timeType == MINISTRY_TIME) {
				dialog.setTitle(Global.res.getString(R.string.title_specify_ministry_time));
			} else {
				dialog.setTitle(Global.res.getString(R.string.title_specify_credit_time));
			}
			
			Button setButton = (Button) dialog.findViewById(R.id.setButton);				
			Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
			final NumberPicker hours = (NumberPicker) dialog.findViewById(R.id.hoursPicker);
			final NumberPicker minutes = (NumberPicker) dialog.findViewById(R.id.minutesPicker);			
			
			OnNumberPickerClosedListener l = new OnNumberPickerClosedListener() {

				@Override
				public void onEvent() {
					
					if (timeType == MINISTRY_TIME) {
						ministryTimeHours = hours.selected;
						ministryTimeMinutes = minutes.selected;
						ministryTimeValue.setText(formatTime(ministryTimeHours,ministryTimeMinutes));
					} else {
						creditTimeHours = hours.selected;
						creditTimeMinutes = minutes.selected;
						creditTimeValue.setText(formatTime(creditTimeHours,creditTimeMinutes));
					}										

					activityContentModified = true;
					dialog.dismiss();	
				}
				
			};
			
			hours.setOnNumberPickerClosedListener(l);
			minutes.setOnNumberPickerClosedListener(l);
			
			if (timeType == MINISTRY_TIME) {
				hours.init(MinistryDetailsActivity.this, 23, ministryTimeHours, true);
				minutes.init(MinistryDetailsActivity.this, 59, ministryTimeMinutes, true);
			} else {
				hours.init(MinistryDetailsActivity.this, 23, creditTimeHours, true);
				minutes.init(MinistryDetailsActivity.this, 59, creditTimeMinutes, true);
			}
			
			setButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					if (timeType == MINISTRY_TIME) {
						ministryTimeHours = hours.selected;
						ministryTimeMinutes = minutes.selected;
						ministryTimeValue.setText(formatTime(ministryTimeHours,ministryTimeMinutes));
					} else {
						creditTimeHours = hours.selected;
						creditTimeMinutes = minutes.selected;
						creditTimeValue.setText(formatTime(creditTimeHours,creditTimeMinutes));
					}
					activityContentModified = true;
					dialog.dismiss();					
				}			
			});
			
			cancelButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					dialog.dismiss();				
				}			
			});		
											
			dialog.show();			
		}
	}
	
	private class OnDataClickListener implements OnClickListener {
		
		private static final int MAGAZINES = 1;
		private static final int BOOKS = 2;		
		private static final int BROCHURES = 3;
		private static final int TRACTS = 4;
		private static final int RETURN_CALLS = 5;
		private static final int VIDEOS = 6;
		
		private int dataType;
		
		public OnDataClickListener(int dataType) {
			super();
			this.dataType = dataType;
		}

		@Override
		public void onClick(View v) {
			final Dialog dialog = new Dialog(MinistryDetailsActivity.this);
			dialog.setContentView(R.layout.number_picker_dialog);
			switch (dataType) {
				case MAGAZINES:
					dialog.setTitle(Global.res.getString(R.string.title_specify_magazines));
					break;
				case BOOKS:
					dialog.setTitle(Global.res.getString(R.string.title_specify_books));
					break;
				case BROCHURES:
					dialog.setTitle(Global.res.getString(R.string.title_specify_brochures));
					break;
				case TRACTS:
					dialog.setTitle(Global.res.getString(R.string.title_specify_tracts));
					break;
				case RETURN_CALLS:
					dialog.setTitle(Global.res.getString(R.string.title_specify_return_calls));
					break;
				case VIDEOS:
					dialog.setTitle(Global.res.getString(R.string.title_specify_videos));
					break;					
			}
			
			Button setButton = (Button) dialog.findViewById(R.id.setButton);				
			Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
			final NumberPicker picker = (NumberPicker) dialog.findViewById(R.id.picker);
			picker.setOnNumberPickerClosedListener(new OnNumberPickerClosedListener() {

				@Override
				public void onEvent() {	
					switch (dataType) {
						case MAGAZINES:
							magazinesValue.setText(""+picker.selected);
							break;
						case BOOKS:
							booksValue.setText(""+picker.selected);
							break;
						case BROCHURES:
							brochuresValue.setText(""+picker.selected);
							break;
						case TRACTS:
							tractsValue.setText(""+picker.selected);
							break;
						case RETURN_CALLS:
							returnCallsValue.setText(""+picker.selected);
							break;
						case VIDEOS:
							videosValue.setText(""+picker.selected);
							break;							
					}

					activityContentModified = true;
					dialog.dismiss();	
				}
				
			});
			switch (dataType) {
				case MAGAZINES:
					picker.init(MinistryDetailsActivity.this, 99, Integer.parseInt(magazinesValue.getText().toString()),false);
					break;
				case BOOKS:
					picker.init(MinistryDetailsActivity.this, 99, Integer.parseInt(booksValue.getText().toString()),false);
					break;
				case BROCHURES:
					picker.init(MinistryDetailsActivity.this, 99, Integer.parseInt(brochuresValue.getText().toString()),false);
					break;
				case TRACTS:
					picker.init(MinistryDetailsActivity.this, 99, Integer.parseInt(tractsValue.getText().toString()),false);
					break;
				case RETURN_CALLS:
					picker.init(MinistryDetailsActivity.this, 99, Integer.parseInt(returnCallsValue.getText().toString()),false);
					break;
				case VIDEOS:
					picker.init(MinistryDetailsActivity.this, 99, Integer.parseInt(videosValue.getText().toString()),false);
					break;					
			}			
			
			setButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					switch (dataType) {
						case MAGAZINES:
							magazinesValue.setText(""+picker.selected);
							break;
						case BOOKS:
							booksValue.setText(""+picker.selected);
							break;
						case BROCHURES:
							brochuresValue.setText(""+picker.selected);
							break;
						case TRACTS:
							tractsValue.setText(""+picker.selected);
							break;
						case RETURN_CALLS:
							returnCallsValue.setText(""+picker.selected);
							break;
						case VIDEOS:
							videosValue.setText(""+picker.selected);
							break;							
					}
					activityContentModified = true;
					dialog.dismiss();					
				}			
			});
			
			cancelButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					dialog.dismiss();				
				}			
			});		
											
			dialog.show();				
		}
	}
	
	@Override
	protected void initializeLayoutIdAndTitle() {
		layoutId = R.layout.ministry_details;
		activityTitle = Global.res.getString(R.string.title_ministry_details);
	}

	@Override
	protected void retrieveViews() { 
        
        ministryTimeValue = (TextView) findViewById(R.id.ministryTimeValue);
        creditTimeValue = (TextView) findViewById(R.id.creditTimeValue);
        magazinesValue = (TextView) findViewById(R.id.magazinesValue);
        booksValue = (TextView) findViewById(R.id.booksValue);
        brochuresValue = (TextView) findViewById(R.id.brochuresValue);
        tractsValue = (TextView) findViewById(R.id.tractsValue);
        videosValue = (TextView) findViewById(R.id.videosValue);
        returnCallsValue = (TextView) findViewById(R.id.returnCallsValue);        
        
        ministryTimeRow = (TableRow) findViewById(R.id.timeRow);
        creditTimeRow = (TableRow) findViewById(R.id.creditTimeRow);
        magazinesRow = (TableRow) findViewById(R.id.magazinesRow);
        booksRow = (TableRow) findViewById(R.id.booksRow);
        brochuresRow = (TableRow) findViewById(R.id.brochuresRow);
        tractsRow = (TableRow) findViewById(R.id.tractsRow);
        videosRow = (TableRow) findViewById(R.id.videosRow);        
        returnCallsRow = (TableRow) findViewById(R.id.returnCallsRow);        
        
        commentsText = (EditText) findViewById(R.id.commentsText);
        
        noCallsView = (TextView) findViewById(R.id.noCallsMessage);         
        callList = (LinearLayout) findViewById(R.id.callList);
        
        saveButton = (Button) findViewById(R.id.saveButton);
        addCallButton = (Button) findViewById(R.id.addCallButton);        
                                      
	}

	@Override
	protected void loadActivityParameters() {
		date = activityParameters.getInt("date");
		month = activityParameters.getInt("month");
		year = activityParameters.getInt("year");
	}
	
	private String formatTime(int hours, int minutes) {
		return hours+" "+Global.res.getString(R.string.label_hour_short)+" "+minutes+" "+Global.res.getString(R.string.label_minute_short);
	}

	@Override
	protected void assignListeners() {		  
        
        commentsText.addTextChangedListener(new EditTextMonitor(this));
        
        ministryTimeRow.setOnClickListener(new OnTimeClickListener(OnTimeClickListener.MINISTRY_TIME));
        creditTimeRow.setOnClickListener(new OnTimeClickListener(OnTimeClickListener.CREDIT_TIME));        

        magazinesRow.setOnClickListener(new OnDataClickListener(OnDataClickListener.MAGAZINES));
        booksRow.setOnClickListener(new OnDataClickListener(OnDataClickListener.BOOKS));
        brochuresRow.setOnClickListener(new OnDataClickListener(OnDataClickListener.BROCHURES));
        tractsRow.setOnClickListener(new OnDataClickListener(OnDataClickListener.TRACTS));
        videosRow.setOnClickListener(new OnDataClickListener(OnDataClickListener.VIDEOS));        
        returnCallsRow.setOnClickListener(new OnDataClickListener(OnDataClickListener.RETURN_CALLS));        
		
        saveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				save();
				finish();
			}
        });
        
        addCallButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				final Dialog dialog = new Dialog(MinistryDetailsActivity.this);
				dialog.setContentView(R.layout.add_call_biblestudy_person_dialog);
				dialog.setTitle(Global.res.getString(R.string.title_add_new_call));
				
				Button saveButton = (Button) dialog.findViewById(R.id.saveButton);				
				Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
				final CheckBox bibleStudyCheckbox = (CheckBox) dialog.findViewById(R.id.bibleStudyConductedCheckbox);
				final Spinner personList = (Spinner) dialog.findViewById(R.id.personSpinner);
				final EditText commentsField = (EditText) dialog.findViewById(R.id.commentsField);				
				
				Cursor c = Database.select("SELECT personid,name FROM persons WHERE timestamp<>"+Global.TIMESTAMP_DELETED+" AND status<>0 ORDER BY name");
				if (c.getCount()==0) {
					c.close();
					Global.displayToast(MinistryDetailsActivity.this, Global.res.getString(R.string.message_no_interested_defined));
					return;
				}
				String[] personNames = new String[c.getCount()];
				final long[] personIds = new long[c.getCount()];				
				int i=0;
				while (c.moveToNext()) {
					personNames[i]=c.getString(c.getColumnIndex("name"));
					personIds[i]=c.getLong(c.getColumnIndex("personid"));
					i++;						
				}				
				c.close();
				
				ArrayAdapter<String> adapter=new ArrayAdapter<String>(MinistryDetailsActivity.this,android.R.layout.simple_spinner_item,personNames);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				personList.setAdapter(adapter);								
				
				saveButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {	
						
						long pid = personIds[personList.getSelectedItemPosition()];
						int bibleStudy = 0;
						if (bibleStudyCheckbox.isChecked())
							bibleStudy = 1;
						
						if (Global.autoIncrementReturnCalls==true) {
							int rc = Integer.parseInt(returnCallsValue.getText().toString());
							returnCallsValue.setText(""+(rc+1));
							activityContentModified = true;
						}
						Database.execSQL("INSERT INTO calls (callid,date,month,year,personid,territoryid,comments,biblestudy,timestamp) VALUES ("+Database.getUniqueRowId("calls")+
								         ","+date+","+month+","+year+","+pid+",0,'"+Global.fixText(commentsField.getText())+"',"+bibleStudy+","+Global.getTimeStamp()+")");	
						dialog.dismiss();
						updateList();
					}			
				});
				
				cancelButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						dialog.dismiss();				
					}			
				});		
				
				dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);								
				dialog.show();							
			}
        });          
        
	}	
	
	private void updateList() {
		
		PopupMenu.createPopupMenu(this);
		PopupMenu.menuSection3.setVisibility(View.GONE);
		PopupMenu.menuSection4.setVisibility(View.GONE);
		
		
		String sql = "SELECT callid,calls.personid AS call_personid,calls.comments AS call_comments,name,biblestudy FROM calls "+
                     "LEFT JOIN persons ON calls.personid=persons.personid WHERE calls.timestamp<>"+Global.TIMESTAMP_DELETED+
                     " AND calls.personid<>0 AND date="+date+" AND month="+month+" AND year="+year;
		
		if (!Global.showInactives) {
			sql = sql + " AND status>0";
		}
		
    	Cursor cursor = Database.select(sql);   		
    	
    	boolean noCallsDefined = true;
    	callList.removeAllViews();

    	while (cursor.moveToNext()) {
    		
    		noCallsDefined=false;
    		ListRow lr = new ListRow(this);
    		
    		lr.setBackgroundDrawable(Global.res.getDrawable(android.R.drawable.list_selector_background));
    		
    		lr.id=cursor.getLong(cursor.getColumnIndex("callid"));
    		
    		lr.firstLine.setText(cursor.getString(cursor.getColumnIndex("name")));

    		lr.secondLine.setText(cursor.getString(cursor.getColumnIndex("call_comments")));
    		int status = cursor.getInt(cursor.getColumnIndex("biblestudy"));
    		if (status == 0)
    			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.call_icon));
    		else
    			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.bible_study));
    		
    		lr.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					ListRow lr = (ListRow) view;
					save();
					clickCall(lr.id);
				}
    			
    		});
    		
            lr.setOnLongClickListener(new OnLongClickListener () {

				@Override
				public boolean onLongClick(View view) {
					ListRow lr = (ListRow) view;
    				final long cid = lr.id;
    				
    				PopupMenu.menuHeading.setText(lr.firstLine.getText());
    				
    				PopupMenu.menuOption1.setText(Global.res.getString(R.string.menuitem_modify_call));		
    				PopupMenu.menuOption2.setText(Global.res.getString(R.string.menuitem_delete_call));						
    				
    				PopupMenu.menuOption1.setOnClickListener(new OnClickListener() {
    					@Override
    					public void onClick(View arg0) {
    						
    						save();
    						
    						PopupMenu.closeMenu();
    						clickCall(cid);				
    					}					
    				});
    				
    				PopupMenu.menuOption2.setOnClickListener(new OnClickListener() {
    					@Override
    					public void onClick(View arg0) {
    						PopupMenu.closeMenu();
    						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MinistryDetailsActivity.this);
    						alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
    						alertDialogBuilder
    							.setMessage(Global.res.getText(R.string.message_delete_call_confirmation))
    							.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
    								public void onClick(DialogInterface dialog,int id) {
    									if (Global.autoIncrementReturnCalls==true) { 
    										int rc = Integer.parseInt(returnCallsValue.getText().toString());
    										if (rc>0) {
    											returnCallsValue.setText(""+(rc-1));
    											activityContentModified = true;
    										}    									
    									}
    									Database.deleteCall(cid);
    									updateList();
    								}
    							  })
    							.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
    								public void onClick(DialogInterface dialog, int id) {
    									dialog.cancel();
    								}
    							});
    				 
    						AlertDialog alertDialog = alertDialogBuilder.create();
    						alertDialog.show();					
    					}					
    				});										
    				
    				PopupMenu.showMenu(view);				
    				
    				return true;
				}
            	
            });     		
    		
    		callList.addView(lr);
    		
    		View horizontalLine = new View(this);
    		horizontalLine.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,1));
    		horizontalLine.setBackgroundColor(0xFF333333);
    		callList.addView(horizontalLine);    		
    		
    	}	
    	cursor.close();
    	
    	if (noCallsDefined) {
    		callList.setVisibility(View.GONE);
    		noCallsView.setVisibility(View.VISIBLE);    		
    	} else {
    		callList.setVisibility(View.VISIBLE);
    		noCallsView.setVisibility(View.GONE);
    	}
    	
	}

	@Override
	protected void updateUi() {
		activityTitleView.setText(activityTitle+" ("+Global.getFormattedDate(year,month,date)+")");				
				
    	if (Global.trackCreditTime==true)
    		creditTimeRow.setVisibility(View.VISIBLE);
    	else
    		creditTimeRow.setVisibility(View.GONE);
    	
    	if (Global.showVideos==true)
    		videosRow.setVisibility(View.VISIBLE);
    	else
    		videosRow.setVisibility(View.GONE);    	
		
		ministryTimeHours = 0;
		ministryTimeMinutes = 0;
		creditTimeHours = 0;
		creditTimeMinutes = 0;		
		magazinesValue.setText(""+0);
		booksValue.setText(""+0);
		brochuresValue.setText(""+0);
		tractsValue.setText(""+0);
		videosValue.setText(""+0);
		returnCallsValue.setText(""+0);		
    	
    	Cursor cursor = Database.select("SELECT * FROM ministry WHERE date="+date+" AND month="+month+" AND year="+year);
    	
    	if (cursor.moveToNext()==true) {
    		newRecord=false;
    		ministryTimeHours = cursor.getInt(cursor.getColumnIndex("hours"));
    		ministryTimeMinutes = cursor.getInt(cursor.getColumnIndex("minutes"));
    		creditTimeHours = cursor.getInt(cursor.getColumnIndex("chours"));
    		creditTimeMinutes = cursor.getInt(cursor.getColumnIndex("cminutes"));    		
    		magazinesValue.setText(""+cursor.getInt(cursor.getColumnIndex("magazines")));
    		booksValue.setText(""+cursor.getInt(cursor.getColumnIndex("books")));
    		brochuresValue.setText(""+cursor.getInt(cursor.getColumnIndex("brochures")));
    		tractsValue.setText(""+cursor.getInt(cursor.getColumnIndex("tracts")));
    		videosValue.setText(""+cursor.getInt(cursor.getColumnIndex("videos")));
    		returnCallsValue.setText(""+cursor.getInt(cursor.getColumnIndex("returncalls")));
    		commentsText.setText(""+cursor.getString(cursor.getColumnIndex("comments")));    		
    	} else
    		newRecord=true;
    	
		ministryTimeValue.setText(formatTime(ministryTimeHours,ministryTimeMinutes)); 
		creditTimeValue.setText(formatTime(creditTimeHours,creditTimeMinutes)); 
    	
    	cursor.close();
    	
    	updateList();
    	
	}    
    
    @Override
    protected void save() {
    	
		activityContentModified = false;		
    	
		if (newRecord==true) {
			Database.execSQL("INSERT INTO ministry (date,month,year,hours,minutes,chours,cminutes,magazines,brochures,tracts,videos,books,returncalls,comments,timestamp) "+
		                            "VALUES ("+date+","+month+","+year+","+ministryTimeHours+","+ministryTimeMinutes+","+creditTimeHours+","+creditTimeMinutes+
		                            ","+magazinesValue.getText()+","+brochuresValue.getText()+","+tractsValue.getText()+","+videosValue.getText()+","+booksValue.getText()+
		                            ","+returnCallsValue.getText()+",'"+Global.fixText(commentsText.getText())+"',"+Global.getTimeStamp()+")");
		} else {
			Database.execSQL("UPDATE ministry SET hours="+ministryTimeHours+", minutes="+ministryTimeMinutes+", "+"chours="+creditTimeHours+", cminutes="+creditTimeMinutes+
					         ", magazines="+magazinesValue.getText()+", tracts="+tractsValue.getText()+", videos="+videosValue.getText()+", brochures="+brochuresValue.getText()+
					         ", books="+booksValue.getText()+", returncalls="+returnCallsValue.getText()+", comments='"+Global.fixText(commentsText.getText())+
					         "', timestamp="+Global.getTimeStamp()+" WHERE date="+date+" AND month="+month+" AND year="+year);
		}				  
		
    }
    
	private void clickCall(long cid) {
		 Intent i = new Intent(getApplicationContext(),CallActivity.class);
	     i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
	     i.putExtra("call_id",cid);			     
	     startActivity(i);		
	}	    

}
